// Decompiled by DJ v3.11.11.95 Copyright 2009 Atanas Neshkov  Date: 22/03/2011 12:24:26 p.m.
// Home Page: http://members.fortunecity.com/neshkov/dj.html  http://www.neshkov.com/dj.html - Check often for new version!
// Decompiler options: packimports(3) 
// Source File Name:   PedidoDetFormWork.java

package com.luxsoft.sw3.impap.ui.form;

import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.swing.AutoCompleteSupport;
import ca.odell.glazedlists.swing.EventTableModel;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.Sizes;
import com.luxsoft.siipap.inventarios.model.Existencia;
import com.luxsoft.siipap.model.Configuracion;
import com.luxsoft.siipap.model.core.Producto;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.service.core.ProductoManager;
import com.luxsoft.siipap.swing.actions.DispatchingAction;
import com.luxsoft.siipap.swing.binding.Binder;
import com.luxsoft.siipap.swing.controls.Header;
import com.luxsoft.siipap.swing.controls.SXTable;
import com.luxsoft.siipap.swing.form2.AbstractForm;
import com.luxsoft.siipap.swing.form2.IFormModel;
import com.luxsoft.siipap.swing.utils.ComponentUtils;
import com.luxsoft.siipap.swing.utils.ResourcesUtils;
import com.luxsoft.siipap.swing.utils.SWExtUIManager;
import com.luxsoft.sw3.impap.ui.selectores.SelectorDeProductos2;
import com.luxsoft.sw3.ventas.PedidoDet;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.PrintStream;
import javax.swing.Action;
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.table.JTableHeader;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.SelectionMapper;

// Referenced classes of package com.luxsoft.sw3.impap.ui.form:
//            PedidoDetFormModel

public class PedidoDetFormWork extends AbstractForm
{

    public PedidoDetFormWork(PedidoDetFormModel model)
    {
        super(model);
        String tipo = model.isCredito() ? "Cr\351dito" : "Contado";
        setTitle((new StringBuilder("Detalle de pedido tipo:")).append(tipo).toString());
        model.getModel("producto").addValueChangeListener(new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent evt)
            {
                if(evt.getNewValue() != null)
                    getControl("cantidad").requestFocusInWindow();
            }
           
        });
    }

    private PedidoDetFormModel getDetModel()
    {
        return (PedidoDetFormModel)getModel();
    }

    protected JComponent buildFormPanel()
    {
        FormLayout layout = new FormLayout("p", "p,2dlu,p,2dlu,t:p:g");
        PanelBuilder builder = new PanelBuilder(layout);
        CellConstraints cc = new CellConstraints();
        builder.add(buildFormMainPanel(), cc.xy(1, 1));
        builder.addSeparator("Disponibilidad", cc.xy(1, 3));
        builder.add(buildDisponibilidadPanel(), cc.xy(1, 5));
        return builder.getPanel();
    }

    protected JComponent buildFormMainPanel()
    {
        FormLayout layout = new FormLayout(" p,2dlu,max(p;60dlu),2dlu,p,2dlu,max(p;60dlu),2dlu,p,2dlu,max(p;60dlu):g", "");
        DefaultFormBuilder builder = new DefaultFormBuilder(layout);
        builder.setLineGapSize(Sizes.DLUX2);
        builder.append("Producto", getControl("producto"), 9);
        builder.append("Cantidad", getControl("cantidad"));
        builder.append("Precio", getControl("precio"));
        builder.append("Imp Bruto", addReadOnly("importeBruto"));
        builder.nextLine();
        builder.append("Comentario", getControl("comentario"), 9);
        builder.nextLine();
        builder.append("");
        builder.nextColumn(6);
        builder.append("Sub Total", addReadOnly("subTotal"));
        ComponentUtils.decorateSpecialFocusTraversal(builder.getPanel());
        JPanel cc = (JPanel)getControl("producto");
        ComponentUtils.decorateTabFocusTraversal(cc);
        return builder.getPanel();
    }

    protected JComponent addReadOnly(String property)
    {
        JComponent res = super.addReadOnly(property);
        res.setBorder(null);
        return res;
    }

    protected JComponent createCustomComponent(String property)
    {
        if("producto".equals(property))
        {
            JComponent pc = createProductosControl();
            return pc;
        }
        if("cantidad".equals(property) || "backOrder".equals(property))
        {
            JComponent c = Binder.createNumberBinding(model.getModel(property), 0);
            return c;
        }
        if("precioCorte".equals(property))
        {
            JComponent c = Binder.createBigDecimalForMonyBinding(model.getModel(property));
            return c;
        }
        if("precio".equals(property))
        {
            JComponent c = Binder.createBigDecimalForMonyBinding(model.getModel(property));
            return c;
        }
        if(property.startsWith("importe"))
        {
            JComponent c = Binder.createBigDecimalForMonyBinding(model.getModel(property));
            return c;
        }
        if(property.startsWith("subTotal"))
        {
            JComponent c = Binder.createBigDecimalForMonyBinding(model.getModel(property));
            return c;
        }
        if(property.startsWith("comentario"))
        {
            JComponent c = Binder.createMayusculasTextField(model.getModel(property));
            return c;
        } else
        {
            return super.createCustomComponent(property);
        }
    }

    private JComponent createProductosControl()
    {
        DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("p:g,2dlu,p", ""));
        JButton bt1 = new JButton(getLookupAction());
        bt1.setFocusable(false);
        bt1.setMnemonic('F');
        final JComboBox box = new JComboBox();
        ca.odell.glazedlists.TextFilterator filterator = GlazedLists.textFilterator(new String[] {
            "clave", "descripcion"
        });
        ca.odell.glazedlists.EventList source = GlazedLists.eventList(getProductos());
        AutoCompleteSupport support = AutoCompleteSupport.install(box, source, filterator);
        support.setFilterMode(1);
        support.setSelectsTextOnFocusGain(true);
        //box.getEditor().addActionListener(new ActionListener() );
        if(model.getValue("producto") != null)
            box.setSelectedItem(model.getValue("producto"));
        builder.append(box);
        builder.append(bt1);
        return builder.getPanel();
    }

    public Action getLookupAction()
    {
        if(lookupAction == null)
        {
            lookupAction = new DispatchingAction(this, "buscarProducto");
            lookupAction.putValue("SmallIcon", ResourcesUtils.getIconFromResource("images/misc2/page_find.png"));
            lookupAction.putValue("Name", "F2");
        }
        return lookupAction;
    }

    protected JComponent buildHeader()
    {
        return getDetModel().getHeader().getHeader();
    }

    protected void onWindowOpened()
    {
        getDetModel().updateHeader();
    }

    private JComponent buildDisponibilidadPanel()
    {
        ca.odell.glazedlists.gui.TableFormat tf = GlazedLists.tableFormat(Existencia.class, new String[] {
            "sucursal.nombre", "cantidad", "recorte", "disponible", "recorteComentario"
        }, new String[] {
            "Sucursal", "Existencia", "Recorte", "Disponible", "Recorte Comentario"
        });
        EventTableModel tm = new EventTableModel(getDetModel().getExistencias(), tf);
        JXTable grid = buildTable();
        grid.setModel(tm);
        grid.setColumnControlVisible(false);
        grid.setFocusable(false);
        grid.packAll();
        JComponent c = ComponentUtils.createTablePanel(grid);
        c.setPreferredSize(new Dimension(220, 120));
        return c;
    }

    public JXTable buildTable()
    {
        JXTable grid = new SXTable();
        grid.setColumnControlVisible(false);
        grid.setHorizontalScrollEnabled(true);
        ColorHighlighter hl = new ColorHighlighter(Color.BLUE, Color.WHITE, new HighlightPredicate() {

            public boolean isHighlighted(Component renderer, ComponentAdapter adapter)
            {
                return (long)adapter.row == getRow().longValue();
            }

            
        }
);
        ColorHighlighter h2 = new ColorHighlighter(Color.WHITE, Color.RED, new HighlightPredicate() {

            public boolean isHighlighted(Component renderer, ComponentAdapter adapter)
            {
                if(adapter.column == 1)
                {
                    Number val = (Number)adapter.getValue();
                    return val.doubleValue() <= 0.0D;
                } else
                {
                    return false;
                }
            }

            
        });
        grid.setHighlighters(new Highlighter[] {
            hl, h2
        });
        grid.setRolloverEnabled(true);
        grid.setSortable(false);
        grid.getSelectionMapper().setEnabled(false);
        grid.getTableHeader().setDefaultRenderer((new JTableHeader()).getDefaultRenderer());
        return grid;
    }

    public void buscarProducto()
    {
        Producto p = SelectorDeProductos2.seleccionar();
        if(p != null)
        {
            model.setValue("producto", p);
            getControl("cantidad").requestFocusInWindow();
        }
    }

    public Long getRow()
    {
        if(row == null)
        {
            String sucursal = System.getProperty("sw3.pedidos.sucursal.row", "0");
            Long id = Long.valueOf(sucursal);
            row = id;
        }
        return row;
    }

    public java.util.List getProductos()
    {
        return productos;
    }

    public void setProductos(java.util.List productos)
    {
        this.productos = productos;
    }

    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable() {

            public void run()
            {
                SWExtUIManager.setup();
                PedidoDet det = PedidoDet.getPedidoDet();
                PedidoDetFormModel model = new PedidoDetFormModel(det);
                model.setSucursal(ServiceLocator2.getConfiguracion().getSucursal());
                PedidoDetFormWork form = new PedidoDetFormWork(model);
                form.setProductos(ServiceLocator2.getProductoManager().buscarProductosActivos());
                form.open();
                if(!form.hasBeenCanceled())
                    System.out.println((new StringBuilder("Ped: ")).append(ToStringBuilder.reflectionToString(model.getBaseBean())).toString());
                System.exit(0);
            }

        }
);
    }

    private java.util.List productos;
    private Action lookupAction;
    private Long row;


}
